package org.laobai.shop.admin.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

import org.apache.commons.codec.binary.Base64;
import org.apache.dubbo.config.annotation.DubboReference;
import org.laobai.shop.goods.entity.Brand;
import org.laobai.shop.goods.entity.Spu;
import org.laobai.shop.goods.service.BrandService;
import org.laobai.shop.goods.service.SpuService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;


@Controller
@RequestMapping("spu")
public class SpuController {
	
	@DubboReference
	private SpuService spuService;
	
	@DubboReference
	private BrandService brandService;
	
	@RequestMapping("list")
	public String spu(int currPage, Spu spu,Model model){
		PageInfo<Spu> page = spuService.page(currPage, spu);
		model.addAttribute("page",page);
		return "/spu/list";
	}
	
	@RequestMapping("toAdd")
	public String toAdd(Model model){
		List<Brand> list = brandService.list();
		model.addAttribute("brands", list);
		return "/spu/add";
	}
	
	@ResponseBody
	@RequestMapping("saveSpu")
	public boolean saveSpu(Spu spu,MultipartFile file){
		InputStream is;
		try {
			is = file.getInputStream();
			byte[] data = new byte[is.available()];
			is.read(data);
			spu.setSmallPic(Base64.encodeBase64String(data));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		return spuService.saveSpu(spu);
	}
	
	
//	@ResponseBody
//	@RequestMapping("saveSpu")
//	public boolean saveSpu(Spu spu,MultipartFile file){
//		/**
//		 1、指定上传目录
//		 2、判断目录是否存在
//		 3、不存在则创建
//		 4、获取文件后缀名
//		 5、获取一个新名字
//		 6、将file写入磁盘
//		 */
//		
//		String path = "D://test//imgs//"+LocalDate.now().toString();
//		File parent = new File(path);
//		// 判断文件是否存在
//		if(!parent.exists()){
//			parent.mkdirs();
//		}
//		
//		// 获取新的文件名
//		String oldName = file.getOriginalFilename();
//		String extName = oldName.substring(oldName.lastIndexOf("."));
//		String newName = System.currentTimeMillis()+extName;
//		
//		try {
//			file.transferTo(new File(parent,newName));
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		
//		spu.setSmallPic(LocalDate.now().toString()+"/"+newName);
//		return spuService.saveSpu(spu);
//	}
	public static void main(String[] args) {
		
		System.out.println(LocalDate.now().toString());
	}
}
